package logic;
import java.io.File;
import java.io.IOException; 
import java.net.DatagramPacket;


public class ThreadDelete implements Runnable{
	private Server server;
	private String[] chunkParts;

	public ThreadDelete(Server server,String[] chunkParts)
	{
		this.setServer(server);
		this.chunkParts=chunkParts;
	}
	public void run() {

		String fileID = chunkParts[1];
		boolean deleted = false;
		for(int i =0; i<Server.getChunkRepository().getChunks().size();i++)
		{
			Chunk chunk = Server.getChunkRepository().getChunks().elementAt(i);

			if(chunk.getFileID().equals(fileID))
			{

				if((new File(chunk.getFileID()+chunk.getChunkNo())).delete())
				{
					Server.getChunkRepository().getChunks().remove(chunk);
					i--;
					deleted=true;
				}

			}
		}
		if(Server.enhancement && deleted)//se estiver a trabalhar com as melhorias
		{
			try {
				byte[] sendData = new byte[65000];
				String reply = new String("DELETED "+Server.VERSION+" "+fileID+Server.CR+Server.LF+Server.CR+Server.LF);
				sendData=reply.getBytes();
				DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, server.getMC_address(), server.getMC_port());

				server.getMC_socket().send(sendPacket);
				
				LogMensage lm=new LogMensage("SEND DELETED FileID: "+fileID);

				Server.logMensagesStr.insertElementAt(lm.str(), 0);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			Server.getChunkRepository().saveInFile(Server.CHUNKS);
		} catch (IOException e) {
			e.printStackTrace();
		}

	} 
	public Server getServer() {
		return server;
	}

	public void setServer(Server server) {
		this.server = server;
	}
}
